package com.ygq.controller;


import DO.PPTDO;
import com.ygq.PPTService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import result.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * 课件上传
 */
@RestController
@RequestMapping("/teacher/ppt")
@Slf4j
public class PPTController {

    @Value("${ygq.path_ppt}")
    private String path;

    @Autowired
    private PPTService pptService;

    // 上传课件
    @PostMapping("/upload")
    public Result<String> ppt(@RequestParam("file") MultipartFile file,
                              @RequestParam("chapterId") Integer chapterId,
                              @RequestParam("classId") Integer classId){
        pptService.savePPT(file,chapterId,classId,path);

        return Result.success(null);
    }

    // 获取课件系列信息
    @GetMapping("/getPPT")
    public Result<List<List<PPTDO>>> getPPT(Integer classId){
        return Result.success(pptService.getPPTByClassId(classId));
    }

    // 获取课件文件
    @GetMapping("/getPPTById")
    public void downloadFile(Integer id, HttpServletResponse response) throws IOException {
        // 查询文件地址
        String address = pptService.getAddress(id);

        // 读到流中
        InputStream inputStream = new FileInputStream(address);// 文件的存放路径
        response.reset();
        response.setContentType("application/octet-stream");
        String filename = new File(address).getName();
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }


    /**
     * 根据id删除课件
     * @param id
     * @return
     */
    @GetMapping("/deletePPT")
    public Result<String> deletePPT(@RequestParam Integer id){
        if (id==null){
            return Result.error("删除失败");
        }
        Integer k = pptService.deletePPT(id);
        if (k == 0){
            return Result.error("系统中没有这个课件");
        }
        return Result.success(null);
    }
}
